import getApiData, { getFrameworkVersion } from '@/services/cpasRequest';
import { getMomentMonthSjnd, intl, removeLocalStorageItem } from '@/utils';
import Form, { Item } from 'devextreme-react/form';
import Popup from 'devextreme-react/popup';
import notify from 'devextreme/ui/notify';
import moment from 'moment';
import React, { useCallback, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import SpinLoading from '../../components/SpinLoading';
import { getPeriodInfo } from '../../tools/service';
import { createDg, getDataGridLookupList, getZcbfInit, initDg, updateZcbfPeriod } from './service';

const NewLocalProject = (props: any, ref: any) => {
  const { getReloadList } = props;
  const { initialState } = useModel('@@initialState');
  const { curUser, settings } = initialState || {};
  const refsForm = useRef<any>();
  const tempReport = useRef<any>();
  const tempDataForm = {
    XMType: '单机审计项目',
    sjxmbh: '',
    sjxmmc: '',
    bsdw: '',
    bsdwxydm: '',
    sjdwxydm: '',
    jtgsxydm: '',
    sjnd: `${new Date().getFullYear()}`,
    RiskLevel: '',
    xmqjs: `${new Date().getFullYear()}-01-01`,
    xmqje: `${new Date().getFullYear()}-12-31`,
    TXName: '',
    TXCode: '',
    // bIntegrat: 0,
    // IsFirstUndertake: 0,
    DGMB: '',
    // HyName: '',
    // HyCode: '',
    UserCode: curUser?.usercode,
    TrueName: curUser?.username,
    reportType: '',
  };
  const [TEMPLETData, setTEMPLETData] = useState<any>([]);
  const [formAllData, setFormAllData] = useState<any>(tempDataForm);
  const [spinLoad, setSpinLoad] = useState<boolean>(false);
  const [openShow, setOpenShow] = useState<boolean>(false);
  const [openTips, setOpenTips] = useState<boolean>(false);
  const [tempDGMB, setTempDGMB] = useState<any>('');
  const [isReadOnly, setIsReadOnly] = useState<boolean>(false);
  const [countNumber, setCountNumber] = useState<number>(0);
  // const [HyData, setHyData] = useState<any>([]);
  const [TXData, setTXData] = useState<any>([]);
  const [DGMBData, setDGMBData] = useState<any>([]);
  const validationFunction = (valueRegExp: string) => {
    const pattern = /^[A-Za-z0-9_-]+$/; // 过滤windows下文件名不支持的字符
    return pattern.test(valueRegExp);
  };
  const [yearData, setYearData] = useState<any>([]);

  const validationRules = {
    sjxmbh: [
      { type: 'required', message: '请输入审计项目编号！' },
      {
        type: 'async',
        message: '请输入有效字符【A-Z;a-z;0-9;-;_;】',
        validationCallback: async (item: any) => {
          return validationFunction(item.value);
        },
      },
    ],
    sjxmmc: [{ type: 'required', message: '请输入审计项目名称！' }],
    bsdw: [{ type: 'required', message: '请输入被审计单位！' }],
    ShortName: [{ type: 'required', message: '请输入被审计单位简称！' }],
    bsdwxydm: [{ type: 'required', message: '请输入被审计单位企业信用代码！' }],
    sjdwxydm: [{ type: 'required', message: '请输入上级单位企业信用代码！' }],
    jtgsxydm: [{ type: 'required', message: '请输入集团公司企业信用代码！' }],

    sjnd: [{ type: 'required', message: '请选择审计年度！' }],
    xmqjs: [
      { type: 'required', message: '请选择开始时间！' },
      {
        type: 'async',
        message: '会计期间开始所在年度不得超出审计年度！',
        validationCallback: async (item: any) => {
          const format = 'YYYY/MM/DD';
          const startTime = moment(item.value, format);
          const sjndYear = moment(formAllData.sjnd, format);
          const res = startTime.isSame(sjndYear, 'year');
          return res;
        },
      },
      {
        type: 'async',
        message: '会计期间开始不能大于会计期间结束',
        validationCallback: async (item: any) => {
          const res = moment(item.value).isBefore(formAllData.xmqje);
          return res;
        },
      },
    ],
    xmqje: [
      { type: 'required', message: '请选择结束时间！' },
      {
        type: 'async',
        message: '会计期间结束所在年度不得超出审计年度！',
        validationCallback: async (item: any) => {
          const format = 'YYYY/MM/DD';
          const endTime = moment(item.value, format);
          const sjndYear = moment(formAllData.sjnd, format);
          const res = endTime.isSame(sjndYear, 'year');
          return res;
        },
      },
      {
        type: 'async',
        message: '会计期间结束不能小于会计期间开始',
        validationCallback: async (item: any) => {
          const res = moment(item.value).isAfter(formAllData.xmqjs);
          return res;
        },
      },
    ],
    TXCode: [{ type: 'required', message: '请选择财务报告体系！' }],
    AuditReportTemplate: [{ type: 'required', message: '请选择报告模板！' }],
    DGMB: [{ type: 'required', message: '请选择底稿模板！' }],
  };

  const setPopupVisible = useCallback((res: boolean) => {
    setOpenShow(res);
  }, []);

  // 编辑获取
  const editLoaclProject = useCallback(
    async (prams: {
      TEMPLETList: string;
      CWBBTXList: string;
      mbTypeList: string;
      projectCode: string;
    }) => {
      // 获取选中的组成部分信息。zcbfData
      const res = await getDataGridLookupList(prams);
      if (res.success) {
        // 编辑存在运来就有的不用管，还有就是老的项目与进行编辑会默认没有reportType，没有时搞一个
        let tempTEMPLET = res.data[prams.TEMPLETList]?.data.map(
          (val: { tempName: string; reportType: string }) => {
            return { displayName: val.tempName, reportType: val.reportType };
          },
        );
        const tempTXData = res.data[prams.CWBBTXList]?.data;
        const tempDGMBData = res.data[prams.mbTypeList]?.data.map((val: { MBMC: string }) => {
          return val.MBMC;
        });
        setTXData(tempTXData);
        setDGMBData(tempDGMBData);
        setTEMPLETData(tempTEMPLET);
        const resInfo = await getApiData('pm.findProjectInfo', { projectBh: prams.projectCode });
        if (resInfo.ok && resInfo.data) {
          const tempObj: any = {
            ...resInfo.data,
            sjnd: resInfo.data.sjnd,
          };

          if (tempObj.TXCode && tempObj.TXName) {
            const resFindTx = tempTXData.find((item: { TXCode: string; TXName: string }) => {
              return item.TXCode === tempObj.TXCode && item.TXName === tempObj.TXName;
            });
            if (!resFindTx) {
              tempObj.TXCode = '';
              tempObj.TXName = '';
            }
          } else {
            tempObj.TXCode = tempTXData[0].TXCode;
            tempObj.TXName = tempTXData[0].TXName;
          }

          if (tempObj.DGMB) {
            const resFindDGMB = tempDGMBData.find((item: string) => {
              return item === tempObj.DGMB;
            });
            if (!resFindDGMB) {
              tempObj.DGMB = '';
            }
          } else {
            tempObj.DGMB = tempDGMBData[0];
          }

          if (tempObj.AuditReportTemplate) {
            const resFindTemplate = tempTEMPLET.find((item: any) => {
              return item.displayName === tempObj.AuditReportTemplate;
            });
            if (!resFindTemplate) {
              tempObj.AuditReportTemplate = '';
            }
          } else {
            tempObj.AuditReportTemplate = tempTEMPLET[0].displayName;
          }
          if (!tempObj?.reportType && tempTEMPLET.length) {
            const arr = tempTEMPLET.filter(
              (a: any) => tempObj.AuditReportTemplate === a.displayName,
            );
            if (arr.length) {
              tempObj.reportType = arr[0].reportType;
            }
          }
          // if (el.AuditReportTemplate) {
          //   const resFindAudit = tempTEMPLET.find((item: any) => {
          //     return item === el.AuditReportTemplate;
          //   });
          //   if (!resFindAudit) {
          //     el.AuditReportTemplate = '';
          //   }
          // } else {
          //   el.AuditReportTemplate = tempTEMPLET[0].TXName;
          // }

          setFormAllData(tempObj);
          setTempDGMB(tempObj.DGMB);
          tempReport.current = tempObj.AuditReportTemplate;
          setPopupVisible(true);
        } else {
          return notify(
            { message: `获取项目信息失败:${res.data}`, position: 'top center', width: 300 },
            'error',
            1000,
          );
        }
      }
    },
    [],
  );

  const changePatternUserCode = () => {
    const pattern = /[^a-zA-Z0-9]/g;
    const projectUser = curUser?.usercode.replace(pattern, '-');
    return projectUser;
  };

  // 新建获取
  const creatLoaclProject = async (
    sjnd: string,
    prams: {
      TEMPLETList: string;
      CWBBTXList: string;
      mbTypeList: string;
    },
  ) => {
    // 用 replace 方法替换非法字符
    const changeUser = changePatternUserCode();
    const res = await getApiData('pm.getProjectCode', { prefix: `${changeUser}-AUD-${sjnd}` });
    if (res.ok) {
      const resList = await getDataGridLookupList(prams);
      if (resList.success) {
        let tempTEMPLET = resList.data[prams.TEMPLETList]?.data.map(
          (val: { tempName: string; reportType: string }) => {
            return { displayName: val.tempName, reportType: val.reportType };
          },
        );
        const tempTXData = resList.data[prams.CWBBTXList]?.data;
        const tempDGMBData = resList.data[prams.mbTypeList]?.data.map((val: { MBMC: string }) => {
          return val.MBMC;
        });
        setTEMPLETData(tempTEMPLET);
        setTXData(tempTXData);
        setDGMBData(tempDGMBData);
        setFormAllData({
          ...tempDataForm,
          ...{
            sjxmbh: res.data.newCode,
            sjnd,
            xmqjs: `${sjnd}-01-01`,
            xmqje: `${sjnd}-12-31`,
            // HyCode: tempHyData[0].MBCode,
            // HyName: tempHyData[0].MBMC,
            TXCode: tempTXData[0].TXCode,
            TXName: tempTXData[0].TXName,
            DGMB: tempDGMBData[0],
            AuditReportTemplate: tempTEMPLET[0].displayName,
            reportType: tempTEMPLET[0].reportType,
          },
        });
        setPopupVisible(true);
      }
    } else {
      notify({ message: `获取项目编号失败！`, position: 'top center' }, 'error', 1000);
    }
  };

  const getSjndYear = () => {
    const nfOptionsArray = new Array();
    const years = new Date().getFullYear();
    for (let i = 2000; i <= years + 20; i++) {
      nfOptionsArray.push(`${i}`);
    }
    return nfOptionsArray;
  };

  useImperativeHandle(ref, () => ({
    showForm: async (isEdit: boolean, selectedRow?: any) => {
      setIsReadOnly(isEdit);
      setYearData(getSjndYear());
      if (isEdit) {
        setCountNumber(999);
        await editLoaclProject({
          TEMPLETList: 'pm.TEMPLETList',
          CWBBTXList: 'pm.CWBBTXList',
          mbTypeList: 'pm.mbTypeList',
          projectCode: selectedRow.projectBh,
        });
      } else {
        setCountNumber(0);
        await creatLoaclProject(`${new Date().getFullYear()}`, {
          TEMPLETList: 'pm.TEMPLETList',
          CWBBTXList: 'pm.CWBBTXList',
          mbTypeList: 'pm.mbTypeList',
        });
      }
    },
  }));

  // 编辑和新建提交
  const creatAndEdit = async () => {
    if (refsForm.current) {
      const devForm: Form = refsForm.current as Form;
      const result: any = await devForm.instance.validate().complete;
      if (tempDGMB !== formAllData.DGMB && isReadOnly && result && result.isValid) {
        return setOpenTips(true);
      }

      if (result && result.isValid) {
        const version = await getFrameworkVersion();
        setSpinLoad(true);
        let moothStr = '';
        moothStr = getMomentMonthSjnd(formAllData.xmqjs, formAllData.xmqje);
        const periodPamas = {
          sjnd: moothStr,
          ADateS: formAllData.xmqjs,
          ADateE: formAllData.xmqje,
          Data_ID: formAllData.sjnd,
          dbName: formAllData.sjxmbh,
        };
        // formAllData.reportType
        try {
          const res = await getApiData('pm.editProject', {
            ...formAllData,
            version,

            // , sjxmmc: escape(formAllData.sjxmmc), bsdw: escape(formAllData.bsdw)
          });
          if (res.ok) {
            if (isReadOnly && tempDGMB === formAllData.DGMB) {
              if (tempReport.current !== formAllData.AuditReportTemplate) {
                getPeriodInfo({ dbname: formAllData.sjxmbh, reportType: formAllData.reportType });
              } else {
                getReloadList(formAllData);
              }
            } else {
              const resInit = await getZcbfInit({
                zcbfid: formAllData.sjxmbh,
                DGMB: formAllData.DGMB,
              });
              if (resInit.success) {
                const resCreate = await createDg(formAllData);
                if (resCreate.success) {
                  notify(
                    { message: `保存成功,初始化成功！`, position: 'top center', width: 300 },
                    'success',
                    1000,
                  );
                }
                if (!isReadOnly) {
                  removeLocalStorageItem(formAllData.sjxmbh);
                }
                const resPeriod = await updateZcbfPeriod(periodPamas);
                if (resPeriod.success) {
                  getPeriodInfo({ dbname: formAllData.sjxmbh, reportType: formAllData.reportType });
                } else {
                  notify(
                    { message: `getPeriodInfo失败！`, position: 'top center', width: 300 },
                    'error',
                    1000,
                  );
                }
              } else {
                notify(
                  {
                    message: `保存成功,初始化失败.失败原因：${res.data}`,
                    position: 'top center',
                    width: 300,
                  },
                  'warning',
                  1000,
                );
              }
              getReloadList(formAllData);
            }
            setPopupVisible(false);
            setSpinLoad(false);
          } else {
            const error = res.data;
            const sear = 'Violation of PRIMARY KEY constraint';
            const isName = error.includes(sear);
            if (isName) {
              notify(
                {
                  message: `保存失败: 该名称【${formAllData?.sjxmbh}】已存在!`,
                  position: 'top center',
                  width: 300,
                },
                'error',
                1000,
              );
            } else {
              notify(
                { message: `保存失败:${error}`, position: 'top center', width: 300 },
                'error',
                1000,
              );
            }
            setSpinLoad(false);
          }
        } catch (error) {
          notify(
            { message: `保存失败:${error}`, position: 'top center', width: 300 },
            'error',
            1000,
          );
          setSpinLoad(false);
        }
      }
    }
  };

  const editProjectDGMB = async () => {
    try {
      setSpinLoad(true);
      const version = await getFrameworkVersion();
      const res = await getApiData('pm.editProject', {
        ...formAllData,
        version,
      });
      debugger;
      if (res.ok) {
        const resInit = await initDg({ zcbfid: formAllData.sjxmbh, mbmc: formAllData.DGMB });
        console.log('创建项目111', resInit, formAllData);
        debugger;
        if (resInit.success) {
          const resCreate = await createDg(formAllData);
          if (resCreate.success) {
            setOpenTips(false);
            notify(
              { message: `保存成功,初始化成功！`, position: 'top center', width: 300 },
              'success',
              1000,
            );
          } else {
            notify(
              {
                message: `保存成功,初始化失败.失败原因：${resCreate.data}`,
                position: 'top center',
                width: 300,
              },
              'warning',
              1000,
            );
          }
        } else {
          notify(
            {
              message: `保存成功,初始化失败.失败原因：${res.data}`,
              position: 'top center',
              width: 300,
            },
            'warning',
            1000,
          );
        }
        setPopupVisible(false);
        setSpinLoad(false);
        getReloadList(formAllData);
      } else {
        const error = res.data;
        const sear = 'Violation of PRIMARY KEY constraint';
        const isName = error.includes(sear);
        if (isName) {
          notify(
            {
              message: `保存失败: 该名称【${formAllData?.sjxmbh}】已存在!`,
              position: 'top center',
              width: 300,
            },
            'error',
            1000,
          );
        } else {
          notify(
            { message: `保存失败:${error}`, position: 'top center', width: 300 },
            'error',
            1000,
          );
        }
        setSpinLoad(false);
      }
    } catch (error) {
      notify({ message: `保存失败:${error}`, position: 'top center', width: 300 }, 'error', 1000);
      setSpinLoad(false);
    }
  };
  const openEditPopup = async (sjnd: number) => {
    const changeUser = changePatternUserCode();
    const res = await getApiData('pm.getProjectCode', { prefix: `${changeUser}-AUD-${sjnd}` });
    if (res.ok) {
      setFormAllData({
        ...formAllData,
        ...{
          sjxmbh: res.data.newCode,
          sjnd,
          xmqjs: `${sjnd}-01-01`,
          xmqje: `${sjnd}-12-31`,
        },
      });
    }
  };

  const validateForm = (e: any) => {
    const updatedField: any = e.dataField;
    const newValue = e.value;
    if (updatedField === 'sjxmmc' && countNumber === 0) {
      setFormAllData({
        ...formAllData,
        ...{
          bsdw: newValue,
        },
      });
      setCountNumber(999);
    } else if (updatedField === 'sjnd' && !isReadOnly) {
      openEditPopup(newValue);
    } else if (updatedField === 'TXCode') {
      const res = TXData.filter((val: { TXCode: string }) => {
        return val.TXCode === newValue;
      });
      if (res.length !== 0) {
        setFormAllData({
          ...formAllData,
          ...{
            TXName: res[0].TXName,
          },
        });
      }
    }
  };

  return (
    <>
      <Popup
        {...props}
        width={600}
        height={720}
        // maxWidth={600}
        // minWidth={600}
        dragOutsideBoundary={true}
        // resizeEnabled={true}
        visible={openShow}
        hideOnOutsideClick={true}
        onHiding={() => {
          setOpenShow(false);
        }}
        toolbarItems={[
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.cancel', '取消'),
              onClick: () => {
                setPopupVisible(false);
                setFormAllData(tempDataForm);
              },
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.ok', '确定'),
              type: 'default',
              onClick: () => {
                creatAndEdit();
              },
            },
          },
        ]}
        contentRender={() => (
          <>
            {spinLoad && <SpinLoading></SpinLoading>}
            <Form
              ref={refsForm}
              formData={formAllData}
              colCount={2}
              labelLocation={'left'}
              labelMode={'outside'}
              focusStateEnabled={true}
              showColonAfterLabel={true}
              alignItemLabels={true}
              onFieldDataChanged={validateForm}
            >
              <Item
                colSpan={2}
                dataField="sjxmbh"
                label={{ text: '项目编号' }}
                validationRules={validationRules.sjxmbh}
                editorOptions={{
                  // valueChangeEvent:"keyup",
                  readOnly: isReadOnly,
                }}
              />
              <Item
                colSpan={2}
                dataField="sjxmmc"
                label={{ text: '项目名称' }}
                validationRules={validationRules.sjxmmc}
                editorOptions={{
                  // valueChangeEvent:"keyup",
                  maxLength: 100,
                }}
              />
              <Item
                colSpan={2}
                dataField="bsdw"
                label={{ text: '被审计单位' }}
                validationRules={validationRules.bsdw}
                editorOptions={{
                  // valueChangeEvent:"keyup",
                  maxLength: 100,
                }}
              />
              <Item
                colSpan={2}
                dataField="ShortName"
                label={{ text: '被审计单位简称' }}
                validationRules={validationRules.ShortName}
                editorOptions={{
                  // valueChangeEvent:"keyup",
                  maxLength: 100,
                }}
              />
              <Item
                colSpan={2}
                dataField="bsdwxydm"
                label={{ text: '被审计单位企业信用代码' }}
                validationRules={validationRules.bsdw}
                editorOptions={{
                  // valueChangeEvent:"keyup",
                  maxLength: 100,
                }}
              />
              <Item
                colSpan={2}
                dataField="sjdwxydm"
                label={{ text: '上级单位企业信用代码' }}
                validationRules={validationRules.sjdwxydm}
                editorOptions={{
                  // valueChangeEvent:"keyup",
                  maxLength: 100,
                }}
              />
              <Item
                colSpan={2}
                dataField="jtgsxydm"
                label={{ text: '集团公司企业信用代码' }}
                validationRules={validationRules.jtgsxydm}
                editorOptions={{
                  // valueChangeEvent:"keyup",
                  maxLength: 100,
                }}
              />
              <Item
                dataField="sjnd"
                editorType="dxSelectBox"
                label={{ text: '审计年度' }}
                editorOptions={{
                  items: yearData,
                  readOnly: isReadOnly,
                  searchEnabled: true,
                  dropDownOptions: {
                    height: 200,
                  },
                }}
                validationRules={validationRules.sjnd}
              />
              <Item
                dataField="RiskLevel"
                label={{ text: '风险级别' }}
                editorType="dxSelectBox"
                editorOptions={{
                  items: settings.riskLevelData,
                }}
              />
              <Item
                dataField="xmqjs"
                label={{ text: '会计期间开始' }}
                editorType="dxDateBox"
                validationRules={validationRules.xmqjs}
              />
              <Item
                dataField="xmqje"
                label={{ text: '会计期间结束' }}
                editorType="dxDateBox"
                validationRules={validationRules.xmqje}
              />
              <Item
                colSpan={2}
                dataField="TXCode"
                label={{ text: '财务报告体系' }}
                editorType="dxSelectBox"
                validationRules={validationRules.TXCode}
                editorOptions={{
                  dataSource: TXData,
                  displayExpr: 'TXName',
                  valueExpr: 'TXCode',
                  searchEnabled: true,
                }}
              />
              <Item
                colSpan={2}
                dataField="AuditReportTemplate"
                label={{ text: '报告模板' }}
                editorType="dxSelectBox"
                validationRules={validationRules.AuditReportTemplate}
                editorOptions={{
                  items: TEMPLETData,
                  searchEnabled: true,
                  // value: displaydataId,
                  valueExpr: 'displayName',
                  displayExpr: 'displayName',
                  onItemClick: async (e: any) => {
                    setFormAllData({ ...formAllData, reportType: e.itemData.reportType });
                  },
                }}
              />
              <Item
                colSpan={2}
                dataField="DGMB"
                label={{ text: '底稿模板' }}
                editorType="dxSelectBox"
                validationRules={validationRules.DGMB}
                editorOptions={{
                  items: DGMBData,
                  searchEnabled: true,
                }}
              />

              {/* company */}
            </Form>
          </>
        )}
      />
      <Popup
        {...props}
        width={600}
        height={200}
        dragOutsideBoundary={true}
        // resizeEnabled={true}
        visible={openTips}
        onHiding={() => {
          setOpenTips(false);
        }}
        toolbarItems={[
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.cancel', '取消'),
              onClick: () => {
                setOpenTips(false);
              },
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.ok', '确定'),
              type: 'default',
              onClick: async () => {
                await editProjectDGMB();
              },
            },
          },
        ]}
        contentRender={() => (
          <>
            {spinLoad && <SpinLoading></SpinLoading>}
            <div>您修改了底稿模板，这将会删除该项目的所有底稿重新生成，是否继续？</div>
          </>
        )}
      />
    </>
  );
};

export default React.forwardRef(NewLocalProject);
